package IOStream;

/*
 * Author: JacksonCoder
 * FileName: ObjectStreamExample
 * Version: 1.0.0
 * Date: 2025/2/26
 */

import java.io.*;

public class ObjectStreamExample {

    public static void main(String[] args) {
        String filePath = "object.dat"; // 序列化对象存储的文件路径

        // 序列化对象
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
            Person person = new Person("张三", 30); // 创建一个可序列化的对象
            oos.writeObject(person); // 序列化对象到文件
            System.out.println("对象已序列化到文件：" + filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化对象
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
            Person person = (Person) ois.readObject(); // 从文件中反序列化对象
            System.out.println("反序列化对象：" + person);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

// 定义一个可序列化的类
class Person implements Serializable {
    private static final long serialVersionUID = 1L; // 序列化版本号
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}
